package com.mingqijia.gassafety.webserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.DtuValveRecord;
import com.mingqijia.gassafety.db.entity.ValveInfo;
import com.mingqijia.gassafety.shared.dto.LogVO;
import com.mingqijia.gassafety.db.mapper.ValveInfoMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.DeviceSolenoidRequest;
import com.mingqijia.gassafety.webserver.request.SolenoidRecordRequest;
import com.mingqijia.gassafety.webserver.request.UnbindSolenoidRequest;
import com.mingqijia.gassafety.webserver.response.DtuValveRecordResponse;
import com.mingqijia.gassafety.webserver.service.DeviceSolenoidService;
import com.mingqijia.gassafety.webserver.service.DtuValveRecordService;
import com.mingqijia.gassafety.webserver.service.ValveInfoService;
import com.mingqijia.gassafety.webserver.utils.LogRecordAspect;
import com.mingqijia.gassafety.webserver.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

import static com.mingqijia.gassafety.shared.constant.OperateRecordEnum.OPERATE_TYPE_14;


/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName DeviceSolenoidServiceImpl.java
 * @Description TODO
 * @createTime 2023年08月21日
 */
@Service
@Slf4j
public class DeviceSolenoidServiceImpl implements DeviceSolenoidService {

    @Autowired
    private EquipmentServiceImpl equipmentService;

    @Autowired
    private DtuValveRecordService dtuValveRecordService;

    @Autowired
    ValveInfoMapper valveInfoMapper;
    @Autowired
    ValveInfoService valveInfoService;

    /**
     * 设备电磁阀操作
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceSolenoid(DeviceSolenoidRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        request.setOptType(request.getOptType()==0?1:0);
        List<Dtu> dtus = equipmentService.checkIMEI(request.getImei());
        if (!CollectionUtils.isEmpty(dtus) && dtus.get(0).getIsDeleted() != 1) {
            Dtu dtu = dtus.get(0);
            Integer solenoidId = dtu.getValveInfoId();
            if (request.getOptType()==1&&solenoidId.equals(request.getSolenoidId()))
                throw new BizException( "已经绑定不能重复绑定！");
            if (request.getOptType()==0&&solenoidId==0)
                throw new BizException( "已经解绑不能重复解绑！");
            log.info("updateDeviceSolenoid-solenoidId:{}", solenoidId);
            QueryWrapper<ValveInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().or().eq(ValveInfo::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(ValveInfo::getId,request.getSolenoidId());
            List<ValveInfo> valveInfos = valveInfoMapper.selectList(queryWrapper);
            log.info("updateDeviceSolenoid-valveInfos:{}", JSONObject.toJSONString(valveInfos));
            if (CollectionUtils.isEmpty(valveInfos)) {
                throw new BizException( "电磁阀不存在！");
            }
            UpdateWrapper<Dtu> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(Dtu::getId, dtu.getId())
                    .eq(Dtu::getIMEI, request.getImei());
            dtu.setValveInfoId(request.getOptType()==1?request.getSolenoidId():0);
            equipmentService.update(dtu, updateWrapper);

            //企业级操作日志
            LogVO vo = new LogVO();
            vo.setConsumerId(dtu.getConsumerId().toString());
            vo.setDetail("关联【电磁阀名称：" + valveInfos.get(0).getValveName() + "】");
            LogRecordAspect.threadLocal.set(vo);

            //记录操作
            DtuValveRecord history = new DtuValveRecord();
            history.setBindChannel(1);
            history.setDeviceId(request.getImei());
            history.setEvent(request.getOptType());
            history.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
            history.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
            history.setRemark(Constants.STR_EMPTY);
            history.setSpId(spId);
            history.setValveId(StringUtils.isEmpty(request.getSolenoidId()) ? solenoidId : request.getSolenoidId());
            dtuValveRecordService.save(history);
            if (request.getOptType()==1&&solenoidId!=0){
                //直接切换关联，需要补解除关联记录
                //记录操作
                DtuValveRecord h = new DtuValveRecord();
                h.setBindChannel(1);
                h.setDeviceId(request.getImei());
                h.setEvent(0);
                h.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
                h.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
                h.setRemark(Constants.STR_EMPTY);
                h.setSpId(spId);
                h.setValveId(solenoidId);
                dtuValveRecordService.save(h);
                //企业级日志
                vo.setOperateRecordEnum(OPERATE_TYPE_14);
                vo.setConsumerId(dtu.getConsumerId().toString());
                ValveInfo oldValve = valveInfoService.getInfoById(solenoidId);
                vo.setDetail("由【电磁阀名称：" + oldValve.getValveName() +  "】变更成【电磁阀名称：" + valveInfos.get(0).getValveName() + "】");
                LogRecordAspect.threadLocal.set(vo);
            }else if (request.getOptType()== 0 && solenoidId != 0){
                //简单的接触关联 类型为解除关联
                //企业级操作日志
                vo.setConsumerId(dtu.getConsumerId().toString());
                vo.setDetail("【电磁阀名称：" + valveInfoService.getInfoById(request.getSolenoidId()).getValveName() + "】");
                LogRecordAspect.threadLocal.set(vo);
            }
        }else {
            throw new BizException( request.getImei()+"不存在！");
        }
    }
    /**
     * 查询关联记录
     *

     * @param request
     * @return
     */
    @Override
    public PageUtil<DtuValveRecordResponse> deviceSolenoidRecord(SolenoidRecordRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        PageUtil<DtuValveRecordResponse> dtuValveRecords = dtuValveRecordService.selectByImei(request, spId);
        return dtuValveRecords;
    }

    /**
     * 解除绑定
     * @param request
     */
    @Override
    public void unbindSolenoid(UnbindSolenoidRequest request) {
        log.info("unbindSolenoid-request:{}",JSONObject.toJSONString(request));
        DeviceSolenoidRequest deviceSolenoidRequest = new DeviceSolenoidRequest();
        BeanUtils.copyProperties(request,deviceSolenoidRequest);
        deviceSolenoidRequest.setOptType(1);
        this.updateDeviceSolenoid(deviceSolenoidRequest);

    }

}